package com.java.controller;

import com.github.pagehelper.PageInfo;
import com.java.domain.JsonBody;
import com.java.domain.SysUser;
import com.java.service.UserService;
import com.java.utils.MD5Utils;
import org.omg.CORBA.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @RequestMapping("/findAll")
    ModelAndView fundAll(
            @RequestParam(value = "currPage", defaultValue = "1", required = false) Integer currPage,
            @RequestParam(value = "pageSize", defaultValue = "5", required = false) Integer pageSize
    ) {
        PageInfo<SysUser> pageInfo = userService.findAllByPage(currPage, pageSize);
        ModelAndView view = new ModelAndView("user-list");
        view.addObject("pageInfo", pageInfo);
        return view;
    }

    @RequestMapping("/save")
    ModelAndView save() {
        return new ModelAndView("user-add");
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    String save(SysUser user) {
        // 对密码进行MD5加密
//        String password = user.getPassword();
//        String md5Password = MD5Utils.md5(password);
//        user.setPassword(md5Password);

        // 加盐加密
        String password = user.getPassword();
        String securityPassword = passwordEncoder.encode(password);
        user.setPassword(securityPassword);

        userService.save(user);
        return "redirect:/user/findAll";
    }

    @ResponseBody
    @RequestMapping(value = "/checkUsername", method = RequestMethod.POST)
    String checkUsername(String username) {
        Boolean b = userService.isUniqueUsername(username);
        return b.toString();
    }

    @RequestMapping("/details")
    ModelAndView details(Integer userId) {
        SysUser user = userService.findDetails(userId);
        ModelAndView view = new ModelAndView("user-show");
        view.addObject("user", user);
        return view;
    }
}
